package com.appspot.yozmcup;

import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;

import com.appspot.yozmcup.DAO.YozmDAO;
import com.appspot.yozmcup.DO.PMF;
import com.appspot.yozmcup.DO.User;
import com.appspot.yozmcup.DO.Winner;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

import java.util.List;
import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.jdo.Query;

public class StartCupServlet extends HttpServlet {
	private static final long serialVersionUID = -7762566610908971670L;
	private final static Logger log = Logger.getLogger(StartCupServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("user");
		String cmd = req.getParameter("cmd");
		String result = "";
		try {
			if(cmd != null && "winner".equals(cmd)){
				PersistenceManager pm = PMF.get().getPersistenceManager();
				Query query = pm.newQuery(Winner.class);
			    query.setOrdering("date asc");
			    query.setRange("0, 300");
			    try {
			        List<Winner> results = (List<Winner>) query.execute();
			        if (!results.isEmpty()) {
		        		result = getUserListModel(results);
			        }
			    } finally {
			        query.closeAll();
			    }
			}else{
				OAuthConsumer consumer = (DefaultOAuthConsumer)session.getAttribute("consumer");
				if(consumer != null){
					String command = "following"; 
					if(cmd != null){
						command = req.getParameter("cmd");
					}
					result = YozmDAO.getMember(consumer, command, user.getUrlName());
				}
			}
		} catch(Exception e) {
			log.warning(e.getMessage());
		}
		res.setContentType("text/xml");
		res.setCharacterEncoding("UTF-8");
		res.getWriter().write(result);
	}
	
	private String getUserListModel(List<Winner> list) throws JSONException{
		JSONObject resultObject = getDefault();
		JSONArray userList = new JSONArray();
		for(Winner winner : list){
			JSONObject user = new JSONObject();
			JSONObject userInfo = getUserInfo(winner.getIntroduce());
			
			user.put("nickname", winner.getNickname());
			user.put("profile_big_img_url", winner.getProfileBigImgUrl());
			user.put("sex_code", winner.getSexCode());
			user.put("url_name", winner.getUrlName());
			
			user.put("user_info", userInfo);
			userList.put(user);
			resultObject.put("user_list", userList);
		}
		return resultObject.toString();
	}
	
	private JSONObject getDefault() throws JSONException{
		JSONObject object = new JSONObject();
		object.put("result_msg", "OK");
		object.put("status", 200);
		object.put("has_more", false);
		return object;
	}
	
	private JSONObject getUserInfo(String introduce) throws JSONException{
		JSONObject object = new JSONObject();
		object.put("introduce", introduce);
		return object;
	}
}
